/********************************************************************************
 * LoginInterceptor.java
 *
 * Created by Jigar Mistry
 * Last modified Date: Sep 4, 2008 8:30:49 AM by Jigar Mistry
 * Version : 0.1
 * Copyright (c) 2008 - 2009 cyberThink Infotech Pvt. Ltd., All rights reserved.
 ********************************************************************************/

package com.printeverywhere.interceptor;

import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Map;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;
import org.apache.struts2.StrutsStatics;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.I18nInterceptor;
import com.opensymphony.xwork2.interceptor.Interceptor;
import com.printeverywhere.delegator.UserServiceDelegator;
import com.printeverywhere.dto.User;
import com.printeverywhere.util.AdminConstants;
import com.printeverywhere.util.AttributeConstants;
import com.printeverywhere.util.CommonUtil;
import com.printeverywhere.util.SearchCriteria;

/**
 * The Class LoginInterceptor.
 */
public class LoginInterceptor implements Interceptor, StrutsStatics {

	/** Logger for this class. */
	private static final Logger logger = Logger.getLogger(LoginInterceptor.class);

	/** The Constant serialVersionUID. */
	private static final long serialVersionUID = 1L;

	/* (non-Javadoc)
	 * @see com.opensymphony.xwork2.interceptor.Interceptor#destroy()
	 */
	public void destroy() {
		// TODO Auto-generated method stub
	}

	/* (non-Javadoc)
	 * @see com.opensymphony.xwork2.interceptor.Interceptor#init()
	 */
	public void init() {
		// TODO Auto-generated method stub
	}

	/* (non-Javadoc)
	 * @see com.opensymphony.xwork2.interceptor.Interceptor#intercept(com.opensymphony.xwork2.ActionInvocation)
	 */
	public String intercept(ActionInvocation invocation) throws Exception {
		if (logger.isDebugEnabled()) {
			logger.debug("intercept(ActionInvocation) - start"); //$NON-NLS-1$
		}

		// Get the action context from the invocation so we can access the
	    // HttpServletRequest and HttpSession objects.
	    final ActionContext context = invocation.getInvocationContext ();
	    HttpServletRequest request = (HttpServletRequest) context.get(HTTP_REQUEST);
	    HttpSession session =  request.getSession (true);

	    // Is there a "user" object stored in the user's HttpSession?
	    Object user = session.getAttribute (AttributeConstants.USER);
	    if (user == null) {
	        // The user has not logged in yet.
	    	String userName = "";
	    	String password = "";

	    	if(request.getCookies() != null) {
		    	Cookie[] cookie = request.getCookies();

		    	for (int index = 0; index < cookie.length; index++) {
		    		if(cookie[index].getName().equals(AttributeConstants.USER_ID))
		    			userName = cookie[index].getValue();
		    		else if(cookie[index].getName().equals(AttributeConstants.PASSWORD))
		    			password = CommonUtil.decrypt(cookie[index].getValue());
		    	}
	    	}

	    	SearchCriteria searchCriteria = new SearchCriteria();
			searchCriteria.setAttribute(AttributeConstants.USER_ID, userName);
			searchCriteria.setAttribute(AttributeConstants.PASSWORD, password);
			List<User> userList = UserServiceDelegator.getList(searchCriteria);

			if(userList.size() > 0) {
				session.setAttribute (AttributeConstants.USER, userList.get(0));
				session.setAttribute(AdminConstants.TEXT,userList.get(0).getLanguages().getText());
				session.setAttribute(I18nInterceptor.DEFAULT_SESSION_ATTRIBUTE, new Locale(userList.get(0).getLanguages().getLanguageCode()));
				return invocation.invoke();
			}

			if (logger.isDebugEnabled()) {
				logger.debug("intercept(ActionInvocation) - end"); //$NON-NLS-1$
			}

			if(!context.getName().equals("login")) {
				session.setAttribute("securedPage", context.getName());
				context.getSession().put("securedPageParams", context.getParameters());
			}

	        return AttributeConstants.LOGIN;
	    } else {
	    	String returnString = invocation.invoke();

	    	if(session.getAttribute("securedPage") != null) {
	    		returnString = session.getAttribute("securedPage").toString();
	    		context.setParameters((Map)context.getSession().get("securedPageParams"));
	    		session.removeAttribute("securedPage");
	    	}

			if (logger.isDebugEnabled()) {
				logger.debug("intercept(ActionInvocation) - end"); //$NON-NLS-1$
			}
	        return returnString;
	    }
	}
}